﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CountriesTowns
{
    public partial class MainForm : Form
    {
        private CountryInfoDataContext dbContext;
        public MainForm()
        {
            InitializeComponent();
            dbContext = new CountryInfoDataContext();
            countryBindingSource.DataSource = dbContext.Countries;
            
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            countryBindingSource.MoveNext();
          
        }

        private void prevButton_Click(object sender, EventArgs e)
        {
            countryBindingSource.MovePrevious();
           
        }

        private void loadImageButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            if (ofd.FileName != null)
            {
                (countryBindingSource.Current as Country).Flag = File.ReadAllBytes(ofd.FileName);
                flagPictureBox.Image = Image.FromFile(ofd.FileName);
                dbContext.SubmitChanges();
            }
        }

        private void countryBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            dbContext.SubmitChanges();
            cityBindingSource.DataSource = (countryBindingSource.Current as Country).Cities;

            if ((countryBindingSource.Current as Country).Flag != null)
            {
                flagPictureBox.Image = Image.FromStream(new MemoryStream((countryBindingSource.Current as Country).Flag.ToArray()));
            }
            else
            {
                flagPictureBox.Image = null;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            dbContext.SubmitChanges();
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
        //    MessageBox.Show((sender as City).CityName) ;
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {

            dbContext.Cities.DeleteOnSubmit((dataGridView1.CurrentRow.DataBoundItem as City));
          //  dataGridView1.DataSource = (countryBindingSource.Current as Country).Cities;
        }
    }
}
